package net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChatServer {
	private ServerSocket ss;
	private List<SocketHandler> clientList = new ArrayList<SocketHandler>();
	private ExecutorService pool = Executors.newCachedThreadPool();
	
	public ChatServer(int port) throws Exception{
		ss = new ServerSocket(port);
		Runnable r = new Runnable(){
			public void run() {
				try {
					while(true){
						Socket s = ss.accept();
						SocketHandler h = new SocketHandler(s);
						pool.execute(h);
						clientList.add(h);
					}
				} catch (Exception e) {
					System.out.println("服务器停止");
				}
			}
		};
		pool.execute(r);
	}
	
	class SocketHandler implements Runnable{
		Socket s;
		BufferedReader in;
		PrintWriter out;
		public SocketHandler(Socket s) throws Exception{
			this.s = s;
			s.setSoTimeout(2000);
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
			send("your ip is "+s.getInetAddress().getHostAddress()+",当前人数是："+(clientList.size()+1));
		}
		
		public void send(String s){
			out.println(s);
			out.flush();
		}
		
		public String receive()throws Exception{
			try {
				return in.readLine();
			} catch (SocketTimeoutException e) {
				send("房主说：");
				send("赶紧说话，不说话就踢人了");
				return "11111111";
			}
			
		}

		public void run() {
			String line;
			try {
				while((line=receive())!=null){
					System.out.println(line);
					if(!line.equals("11111111")){
						for (SocketHandler sh : clientList) {
							sh.send(s.getInetAddress().toString()+"说：");
							sh.send(line);
						}
					}
					
				}
				//客户端断开
				clientList.remove(this);
			} catch (Exception e) {
				//客户端断开
				clientList.remove(this);
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) throws Exception {
		ChatServer cs = new ChatServer(8000);
	}
}
